package com.yoosora.repository.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.yoosora.common.mode.Operators;
import com.yoosora.dao.dataobj.PluginDO;
import com.yoosora.dao.mapper.PluginDOMapper;
import com.yoosora.model.PluginDTO;
import com.yoosora.repository.PluginRepository;
import com.yoosora.utils.DOUtils;
import com.yoosora.utils.DTOConvUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author yoosora
 */
@Repository
public class PluginRepositoryImpl implements PluginRepository {

	@Autowired
	private PluginDOMapper mapper;
	
	private PluginDTO conv(PluginDO record){
		final PluginDTO dto = new PluginDTO();
		dto.setId(record.getId());
		dto.setName(record.getName());
		dto.setPackageName(record.getPackageName());
		dto.setIsActive(record.getIsActive());
		dto.setDetail(record.getDetail());
		DTOConvUtils.copyBasicProperties(record, dto);
		return dto;
	}
	
	@Override
	public void insert(PluginDO record, Operators operators) {
		DOUtils.setDefaultInsertFields(record, operators);
		mapper.insert(record);
	}

	@Override
	public void update(PluginDO record, Operators operators) {
		DOUtils.setDefaultUpdateFields(record, operators);
		PluginDO entity = new PluginDO();
		entity.setId(record.getId());
		entity.setDeleted(Boolean.FALSE);
		QueryWrapper<PluginDO> qw = new QueryWrapper<>(entity);
		mapper.update(record, qw);
	}

	@Override
	public boolean delete(Long id, Operators operators) {
		PluginDO entity = new PluginDO();
		entity.setId(id);
		entity.setDeleted(Boolean.TRUE);
		return 1 == mapper.updateById(entity);
	}

	@Override
	public PluginDTO queryByPK(Long id) {
		PluginDO entity = mapper.selectById(id);
		return null == entity || Boolean.TRUE.equals(entity.getDeleted()) ? null : conv(entity);
	}

	@Override
	public long count(Wrapper<PluginDO> qw) {
		return mapper.selectCount(qw);
	}

	@Override
	public List<PluginDTO> queryPage(IPage<PluginDO> iPage, Wrapper<PluginDO> qw) {
		return mapper.selectPage(iPage, qw).getRecords().stream().map(this::conv).collect(Collectors.toList());
	}

	@Override
	public List<PluginDTO> queryWrapper(Wrapper<PluginDO> qw) {
		return mapper.selectList(qw).stream().map(this::conv).collect(Collectors.toList());
	}
}
